import {reqShopCartList,reqDeleteCart,reqUpdateChecked} from '@/api'
const state = {
    cartList:[]
};
const mutations = {
    GETCARTLIST(state,cartList){
        state.cartList = cartList
    }
};
const actions = {
    async getCartList({commit}){
        let result = await reqShopCartList();
        if(result.code === 200){
            commit('GETCARTLIST',result.data)
        }
    },
    async deleteCartList({commit},skuId){
        let result = await reqDeleteCart(skuId);
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('Request Failed'))
        }
    },
    async updateChecked({commit},{skuId,isChecked}){
        let  result = await reqUpdateChecked(skuId,isChecked);
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('Request Failed'))
        }
    },
    deleteAllChecked({dispatch,getters}){
        let promises = []
        getters.cartList.cartInfoList.forEach((item) => {
            let promise = item.isChecked==1? dispatch('deleteCartList',item.skuId):'';
            promises.push(promise)
        })
        return Promise.all(promises);
    },
    updateAllChecked({dispatch,state},isChecked){
        let promises = [];
        console.log(state.cartList);
        state.cartList[0].cartInfoList.forEach((item) => {
            let promise = dispatch('updateChecked',{skuId:item.skuId,isChecked});
            promises.push(promise)
        })
        return Promise.all(promises);
    }
};
const getters = {
    cartList(state){
        return state.cartList[0]||{}
    }
};
export default{
    state,
    mutations,
    actions,
    getters
}